const Router = require('@koa/router');
const { Indent, User, Ticket, Jingdian } = require('../databases');

const indentRouter = new Router({
    prefix: '/indent'
});

// 获取订单首页
indentRouter.get('/', (ctx, next) => {
    ctx.body = {
        code: 200,
        message: '订单首页',
        data: 'Welcome to indent API',
    };
});

// 创建订单
indentRouter.post('/create', async (ctx, next) => {
    try {
        const { uid, tid, jid, quantity, totalPrice } = ctx.request.body;
        
        // 验证用户是否存在
        const user = await User.findByPk(uid);
        if (!user) {
            ctx.body = {
                code: 404,
                message: '用户不存在',
                data: null
            };
            return;
        }

        // 验证门票是否存在
        const ticket = await Ticket.findByPk(tid);
        if (!ticket) {
            ctx.body = {
                code: 404,
                message: '门票不存在',
                data: null
            };
            return;
        }

        // 验证景点是否存在
        const jingdian = await Jingdian.findByPk(jid);
        if (!jingdian) {
            ctx.body = {
                code: 404,
                message: '景点不存在',
                data: null
            };
            return;
        }

        const indent = await Indent.create({
            uid,
            tid,
            jid,
            quantity,
            totalPrice,
            status: 'pending'
        });

        ctx.body = {
            code: 200,
            message: '创建订单成功',
            data: indent,
        };
    } catch (error) {
        ctx.body = {
            code: 500,
            message: '创建订单失败',
            error: error.message
        };
    }
});

// 获取所有订单列表
indentRouter.get('/list', async (ctx, next) => {
    try {
        const indents = await Indent.findAll({
            include: [
                {
                    model: User,
                    as: 'user',
                    attributes: ['uid', 'username']
                },
                {
                    model: Ticket,
                    as: 'ticket',
                    attributes: ['tid', 'name', 'desc']
                },
                {
                    model: Jingdian,
                    as: 'jingdian',
                    attributes: ['jid', 'name', 'desc']
                }
            ],
            order: [['createAt', 'DESC']]
        });
        
        ctx.body = {
            code: 200,
            message: '获取订单列表成功',
            data: indents,
        };
    } catch (error) {
        ctx.body = {
            code: 500,
            message: '获取订单列表失败',
            error: error.message
        };
    }
});

// 根据ID获取订单详情
indentRouter.get('/:id', async (ctx, next) => {
    try {
        const { id } = ctx.params;
        const indent = await Indent.findByPk(id, {
            include: [
                {
                    model: User,
                    as: 'user',
                    attributes: ['uid', 'username']
                },
                {
                    model: Ticket,
                    as: 'ticket',
                    attributes: ['tid', 'name', 'desc', 'content']
                },
                {
                    model: Jingdian,
                    as: 'jingdian',
                    attributes: ['jid', 'name', 'desc', 'logoRemoteImageUrl']
                }
            ]
        });

        if (!indent) {
            ctx.body = {
                code: 404,
                message: '订单不存在',
                data: null
            };
            return;
        }

        ctx.body = {
            code: 200,
            message: '获取订单详情成功',
            data: indent,
        };
    } catch (error) {
        ctx.body = {
            code: 500,
            message: '获取订单详情失败',
            error: error.message
        };
    }
});

// 更新订单状态
indentRouter.put('/:id/status', async (ctx, next) => {
    try {
        const { id } = ctx.params;
        const { status } = ctx.request.body;

        const indent = await Indent.findByPk(id);
        if (!indent) {
            ctx.body = {
                code: 404,
                message: '订单不存在',
                data: null
            };
            return;
        }

        await indent.update({
            status,
            payAt: status === 'paid' ? new Date() : indent.payAt
        });

        ctx.body = {
            code: 200,
            message: '更新订单状态成功',
            data: indent,
        };
    } catch (error) {
        ctx.body = {
            code: 500,
            message: '更新订单状态失败',
            error: error.message
        };
    }
});

// 根据用户ID获取订单列表
indentRouter.get('/user/:userId', async (ctx, next) => {
    try {
        const { userId } = ctx.params;
        
        const user = await User.findByPk(userId);
        if (!user) {
            ctx.body = {
                code: 404,
                message: '用户不存在',
                data: null
            };
            return;
        }

        const indents = await Indent.findAll({
            where: { uid: userId },
            include: [
                {
                    model: Ticket,
                    as: 'ticket',
                    attributes: ['tid', 'name', 'desc']
                },
                {
                    model: Jingdian,
                    as: 'jingdian',
                    attributes: ['jid', 'name', 'desc']
                }
            ],
            order: [['createAt', 'DESC']]
        });

        ctx.body = {
            code: 200,
            message: '获取用户订单列表成功',
            data: indents,
        };
    } catch (error) {
        ctx.body = {
            code: 500,
            message: '获取用户订单列表失败',
            error: error.message
        };
    }
});

// 根据状态获取订单列表
indentRouter.get('/status/:status', async (ctx, next) => {
    try {
        const { status } = ctx.params;
        const indents = await Indent.findAll({
            where: { status },
            include: [
                {
                    model: User,
                    as: 'user',
                    attributes: ['uid', 'username']
                },
                {
                    model: Ticket,
                    as: 'ticket',
                    attributes: ['tid', 'name', 'desc']
                },
                {
                    model: Jingdian,
                    as: 'jingdian',
                    attributes: ['jid', 'name', 'desc']
                }
            ],
            order: [['createAt', 'DESC']]
        });

        ctx.body = {
            code: 200,
            message: '获取状态订单列表成功',
            data: indents,
        };
    } catch (error) {
        ctx.body = {
            code: 500,
            message: '获取状态订单列表失败',
            error: error.message
        };
    }
});

// 删除订单
indentRouter.delete('/:id', async (ctx, next) => {
    try {
        const { id } = ctx.params;
        
        const indent = await Indent.findByPk(id);
        if (!indent) {
            ctx.body = {
                code: 404,
                message: '订单不存在',
                data: null
            };
            return;
        }

        // 只有待支付和已取消的订单才能删除
        if (indent.status === 'paid' || indent.status === 'completed') {
            ctx.body = {
                code: 400,
                message: '已支付或已完成的订单不能删除',
                data: null
            };
            return;
        }

        await indent.destroy();

        ctx.body = {
            code: 200,
            message: '删除订单成功',
            data: null,
        };
    } catch (error) {
        ctx.body = {
            code: 500,
            message: '删除订单失败',
            error: error.message
        };
    }
});

module.exports = indentRouter;
